package com.redu.controller;

import java.util.HashMap;
import java.util.Map;

import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.google.gson.Gson;
import com.redu.bean.Course;
import com.redu.bean.StudentCourse;
import com.redu.bean.Student;
import com.redu.service.StudentCourseService;

@RestController
@RequestMapping("/studentCourse")
public class StudentCourseController {
	
	@Autowired
	private StudentCourseService studentCourseService;
	
	@RequestMapping("/chooseCourse")
	public String chooseCourse(int sid,int cid){
		Student student=new Student();
		Course course = new Course();
		student.setSid(sid);
		course.setCid(cid);
		StudentCourse studentCourse = new StudentCourse();
		studentCourse.setStudent(student);
		studentCourse.setCourse(course);
		return new Gson().toJson(studentCourseService.chooseCourse(studentCourse));
	}
	
	@RequestMapping("/listPage")
	public String listPageCourse(int page,int rows,String cname){
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("offset", (page-1)*rows);
		map.put("size",rows);
		Map<String,Object>result=new HashMap<String,Object>();
		result.put("total", studentCourseService.getCount(map));
		result.put("rows", studentCourseService.listPage(map));
		return new Gson().toJson(result);
	}
	
	@RequestMapping("/marking")
	public String marking(int sid,int cid,int score){
		Student student=new Student();
		Course course = new Course();
		student.setSid(sid);
		course.setCid(cid);
		StudentCourse studentCourse = new StudentCourse();
		studentCourse.setStudent(student);
		studentCourse.setCourse(course);
		studentCourse.setScore(score);
		return new Gson().toJson(studentCourseService.marking(studentCourse));
	}
	
	/**
	 * 删除
	 * @param sids
	 * @param cids
	 * @return
	 */
	@RequestMapping("/delete")
	public String chooseCourse(@RequestParam("sids[]")int[] sids,@RequestParam("cids[]")int[] cids){
		Gson gson = new Gson();
		
		//将参数打包
		if(sids==null || cids==null) return gson.toJson("false");
		if(sids.length!=cids.length) return gson.toJson("false");
		
		int len = sids.length;
		StudentCourse[] studentCourses = new StudentCourse[len];
		for(int i=0;i<len;i++){
			Student student = new Student();
			Course course = new Course();
			student.setSid(sids[i]);
			course.setCid(cids[i]);
			studentCourses[i] = new StudentCourse();
			studentCourses[i].setStudent(student);
			studentCourses[i].setCourse(course);
		}
		return gson.toJson(studentCourseService.delete(studentCourses));
	}
}
